"use strict";

var express = require('express');
var UUID = require('uuid')
var dt = require('date-utils')
var util = require('util')
var MyUtils = require('./../util/utils')
var fs = require("fs")
var multer = require('multer')


var uploadFolder = './../../patch-file/'
var createFolder = function (folder) {
    try {
        fs.accessSync(folder)
    } catch (e) {
        fs.mkdirSync(folder)
    }
}
createFolder(uploadFolder)
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, uploadFolder);
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
    }
});

var upload = multer({storage: storage}).single('patch')

var connection = require('./../constant/mysqlconnection').connection

var router = express.Router();
var myUtils = new MyUtils()

router.use(function (req, res, next) {
// todo 判断用户是否登陆
    next()
})

router.post('/createPatch', function (req, res, next) {
    // 判断应用版本号是否存在
    // 获取当前版本号下的补丁文件数量
    // SELECT version.app_version_name,ptch.appversion_id,ptch.logic_delete_flag FROM appversion version join patch ptch
    // on version.id = ptch.appversion_id WHERE version.logic_delete_flag = '01'
    // and version.id = '56253400-b34a-11e7-a91b-b55aa5a24761'
    var searchSql = 'select version.app_version_name ,  ptch.logic_delete_flag from appversion version left join patch ptch on ' +
        'version.id = ptch.appversion_id where version.logic_delete_flag = 01 and version.id = ?'
    var searchSqlParams = [
        req.body.appVersionId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            if (results.length == 0) {
                // 说明当前应用版本号不存在
                var bizFailureModel = myUtils.generateSuccess()
                bizFailureModel.model = {
                    success: 1,
                    info: '请先创建应用版本号再添加补丁文件'
                }
                res.end(JSON.stringify(bizFailureModel))
            } else {
                req.body.appVersionName = results[0].app_version_name
                var lastPatchCode = 0
                for (var i = 0, len = results.length; i < len; i++) {
                    if (results[i].logic_delete_flag === '01') {
                        lastPatchCode++
                    }
                }
                console.log(lastPatchCode)
                req.body.lastPatchCode = ++lastPatchCode
                next('route')
            }
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.post('/createPatch', function (req, res) {
    var insertSql = 'insert into patch(id,patch_name,description,patch_size,patch_code,patch_path,appversion_id,appversion_name,create_time,update_time,download_number,compose_number,patch_md5,logic_delete_flag) values ' +
        '(?,?,?,?,?,?,?,?,?,?,?,?,?,\'01\')'
    var patchId = UUID.v1()
    var insertSqlParams = [
        patchId,
        req.body.patchName,
        req.body.patchDescription,
        req.body.patchSize,
        req.body.lastPatchCode,
        req.body.patchPath,
        req.body.appVersionId,
        req.body.appVersionName,
        new Date().toFormat('YYYY-MM-DD HH24:MI:SS'),
        new Date().toFormat('YYYY-MM-DD HH24:MI:SS'),
        0,
        0,
        req.body.md5
    ]
    connection.query(insertSql, insertSqlParams, function (error, result) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                info: '补丁包创建成功',
                patchCode: req.body.lastPatchCode,
                patchId: patchId
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            console.log(error)
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})
router.put('/updateDownloadCountByPatchId', function (req, res) {
    updatePatchCnt(false, req, res)
})

router.put('/updateCompositeCntByPatchId', function (req, res) {
    updatePatchCnt(true, req, res)
})

router.put("/updateDownloadCntByMD5", function (req, res) {
    increasePatchCntByMD5(false, req, res)
})

router.put('/updateCompositeByMD5', function (req, res) {
    increasePatchCntByMD5(true, req, res)
})

function increasePatchCntByMD5(isCompose, req, res) {
    // var searchSql = 'select compose_number from patch where patch_md5 = ? and logic_delete_flag = 01'
    var searchSql = 'select ' + (isCompose ? 'compose_number' : 'download_number') + ' from patch where patch_md5 = ? and logic_delete_flag = 01'
    var searchSqlParams = [req.body.md5]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            if (results.length >= 1) {
                var updateSql = 'update patch set ' + (isCompose ? 'compose_number' : 'download_number') + ' = ? , update_time = ? where patch_md5 = ?'
                var newNum = isCompose ? (results[0].compose_number + 1) : (results[0].download_number + 1)
                var updateSqlParams = [newNum, new Date().toFormat('YYYY-MM-DD HH24:MI:SS'), req.body.md5]
                connection.query(updateSql, updateSqlParams, function (err, mRes) {
                    if (!err) {
                        var bizSucModel = myUtils.generateSuccess()
                        bizSucModel.model = {
                            success: 0,
                            info: '更新成功'
                        }
                        res.end(JSON.stringify(bizSucModel))
                    } else {
                        res.end(JSON.stringify(myUtils.generateInnerError()))
                    }
                })
            } else {
                var bizModel = myUtils.generateSuccess()
                bizModel.model = {
                    success: 1,
                    info: '补丁文件不存在'
                }
                res.end(JSON.stringify(bizModel))
            }
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
}


function updatePatchCnt(isCompose, req, res) {
    var searchSql = 'select ' + (isCompose ? 'compose_number' : 'download_number') + ' from patch where id = ? and logic_delete_flag = 01'
    var searchSqlParams = [req.body.patchId]
    connection.query(searchSql, searchSqlParams, function (err, results) {
        if (!err) {
            if (results.length >= 1) {
                var updateSql = 'update patch set ' + (isCompose ? 'compose_number' : 'download_number') + ' = ? ' +
                    ',update_time = ?' +
                    ' where id = ?'
                var updateSqlParams = [
                    isCompose ? results[0].compose_number + 1 : results[0].download_number + 1,
                    new Date().toFormat('YYYY-MM-DD HH24:MI:SS'),
                    req.body.patchId
                ]
                connection.query(updateSql, updateSqlParams, function (error, result) {
                    if (!error) {
                        var bizSucModel = myUtils.generateSuccess()
                        bizSucModel.model = {
                            success: 0,
                            info: '更新成功'
                        }
                        res.end(JSON.stringify(bizSucModel))
                    } else {
                        res.end(JSON.stringify(myUtils.generateInnerError()))
                    }
                })
            } else {
                var bizModel = myUtils.generateSuccess()
                bizModel.model = {
                    success: 1,
                    info: '补丁文件不存在'
                }
                res.end(JSON.stringify(bizModel))
            }
        } else {
            JSON.stringify(myUtils.generateInnerError())
        }
    })
}

router.delete('/deletePatch', function (req, res) {
    var updateSql = 'update patch set logic_delete_flag = 99 where id = ?'
    var updateSqlParams = [
        req.body.patchId
    ]
    connection.query(updateSql, updateSqlParams, function (error, result) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            if (result.affectedRows == 1) {
                // 逻辑删除成功
                bizSucModel.model = {
                    success: 0,
                    info: '删除成功'
                }
            } else {
                bizSucModel.model = {
                    success: 1,
                    info: '补丁文件不存在，无效删除'
                }
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.get('/patchList', function (req, res) {
    var searchSql = 'SELECT * FROM patch WHERE logic_delete_flag = 01 AND appversion_id = ? ORDER BY create_time DESC LIMIT ' + (parseInt(req.query.page) - 1) + ',' + req.query.size
    var searchSqlParams = [
        req.query.appVersionId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: '0',
                patchList: results
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.post('/upload', function (req, res) {
    // console.log(req.file)
    upload(req, res, function (err) {
        if (!err) {
            var file = req.file
            console.log('文件类型：' + file.mimetype)
            console.log('原始文件名：' + file.originalname)
            console.log('文件大小：' + file.size)
            // 上传成功
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                file: {
                    size: file.size,
                    path: 'patch-file/' + file.filename
                },
                info: '上传成功'
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            // 上传失败
            console.log('upload error : ' + err)
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})


router.get('/getPatchInfo', function (req, res) {
    var querySql = 'select * from patch where id = ? and logic_delete_flag = 01'
    var querySqlParams = [req.query.id]
    connection.query(querySql, querySqlParams, function (error, results) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            if (results.length > 0) {
                bizSucModel.model = {
                    success: 0,
                    patchInfo: results[0]
                }
                res.end(JSON.stringify(bizSucModel))
            } else {
                bizSucModel.model = {
                    success: 1,
                    info: "补丁文件不存在"
                }
                res.end(JSON.stringify(bizSucModel))
            }
        } else {
            res.end(JSON.string(myUtils.generateInnerError()))
        }
    })
})

router.put('/updatePatch', function (req, res) {
    var updateSql = 'update patch set '
    var updateSqlParams = []
    var name = req.body.patchName
    var i = 0
    if (typeof name !== 'undefined') {
        updateSql += 'patch_name = ?,'
        updateSqlParams[i++] = name
    }
    var des = req.body.description
    if (typeof name !== 'undefined') {
        updateSql += 'description = ?,'
        updateSqlParams[i++] = des
    }
    updateSql += 'update_time = ?' + ' where id = ? and logic_delete_flag = 01'
    updateSqlParams[i++] = new Date().toFormat('YYYY-MM-DD HH24:MI:SS')
    updateSqlParams[i++] = req.body.patchId
    connection.query(updateSql, updateSqlParams, function (error, results) {
        if (!error) {
            var bizModel = myUtils.generateSuccess()
            if (results.affectedRows > 0) {
                bizModel.model = {
                    success: 0,
                    info: '更新成功'
                }
            } else {
                bizModel.model = {
                    success: 1,
                    info: '补丁文件不存在'
                }
            }
            res.end(JSON.stringify(bizModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.get('/getNewestPatch', function (req, res) {
    var searchSql = 'select ptch.patch_md5,ptch.patch_path , ptch.patch_code from patch ptch left join appversion aversion on ptch.appversion_id = aversion.id ' +
        'where aversion.application_id = ? and aversion.app_version_name = ? and ptch.logic_delete_flag = 01'
    var searchSqlParams = [
        req.query.appId,
        req.query.appVersionName
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        console.log('err = ' + error)
        if (!error) {
            var bizModel = myUtils.generateSuccess()
            if (results.length == 0) {
                // 说明当前版本不存在最新补丁包信息
                bizModel.model = {
                    success: 1,
                    info: '无最新补丁包'
                }
            } else {
                bizModel.model = {
                    success: 0,
                    patch: findNewestPatch(results)
                }
            }
            res.end(JSON.stringify(bizModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})
function findNewestPatch(results) {
    var newestPatchInfo = results[0]
    for (var i = 1, len = results.length; i < len; i++) {
        if (newestPatchInfo.patch_code < results[i].patch_code) {
            newestPatchInfo = results[i]
        }
    }
    return newestPatchInfo
}

module.exports = router

